#include <windows.h>
#include "Tetromino.h"
#include <iostream>
#include <string>

int grid[GRID_HEIGHT][GRID_WIDTH] = {}; // 定义并初始化
COLORREF colors[GRID_HEIGHT][GRID_WIDTH] = {}; // 定义并初始化
int score = 0;

Tetromino currentTetromino;
HWND hPauseButton;
HWND hRestartButton;

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
    static bool isGameStarted = true; // 直接开始游戏
    static bool isPaused = false; // 游戏状态，初始为未暂停

    switch (msg) {
    case WM_PAINT: {
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hwnd, &ps);

        // 创建内存设备上下文
        HDC memDC = CreateCompatibleDC(hdc);
        HBITMAP memBitmap = CreateCompatibleBitmap(hdc, 400, 500);
        SelectObject(memDC, memBitmap);

        // 清除内存 DC 背景
        RECT rect = { 0, 0, 400, 500 };
        FillRect(memDC, &rect, (HBRUSH)(COLOR_WINDOW + 1)); // 使用默认窗口背景色

        // 设置网格线颜色为淡灰色
        HPEN pen = CreatePen(PS_SOLID, 1, RGB(200, 200, 200)); // 创建淡灰色画笔
        SelectObject(memDC, pen); // 选择画笔

        // 绘制网格
        for (int i = 0; i <= GRID_HEIGHT; ++i) {
            MoveToEx(memDC, 0, i * 20, NULL);
            LineTo(memDC, GRID_WIDTH * 20, i * 20); // 横线
        }
        for (int j = 0; j <= GRID_WIDTH; ++j) {
            MoveToEx(memDC, j * 20, 0, NULL);
            LineTo(memDC, j * 20, GRID_HEIGHT * 20); // 竖线
        }

        // 绘制已固定的方块
        for (int i = 0; i < GRID_HEIGHT; ++i) {
            for (int j = 0; j < GRID_WIDTH; ++j) {
                if (grid[i][j] != 0) {
                    // 绘制固定方块
                    HBRUSH brush = CreateSolidBrush(colors[i][j]);
                    SelectObject(memDC, brush);
                    Rectangle(memDC, j * 20, i * 20, (j + 1) * 20, (i + 1) * 20);
                    DeleteObject(brush);
                }
            }
        }

        // 绘制当前方块
        currentTetromino.Draw(memDC); // 确保这个方法绘制当前方块

        // 显示分数
        std::wstring scoreText = L"分数: " + std::to_wstring(score);
        SetTextColor(memDC, RGB(0, 0, 0)); // 设置字体颜色
        SetBkMode(memDC, TRANSPARENT); // 设置背景模式为透明
        TextOut(memDC, 10, 50, scoreText.c_str(), scoreText.length()); // 在(50, 50)位置绘制得分

        if (!isGameStarted) {
            TextOut(memDC, 50, 100, L"Press SPACE to Start", 20);
        }
        else if (isPaused) {
            TextOut(memDC, 50, 150, L"Game Paused", 12); // 显示暂停信息
        }

        // 将内存 DC 的内容复制到屏幕
        BitBlt(hdc, 0, 0, 400, 500, memDC, 0, 0, SRCCOPY);

        // 清理
        DeleteObject(memBitmap);
        DeleteDC(memDC);
        DeleteObject(pen); // 记得删除画笔

        EndPaint(hwnd, &ps);
    } break;

    case WM_TIMER:
        if (isGameStarted && !isPaused) { // 确保游戏开始且未暂停
            if (currentTetromino.IsAtBottom()) {
                // 固定当前方块到网格
                for (int i = 0; i < currentTetromino.shape.size(); ++i) {
                    for (int j = 0; j < currentTetromino.shape[i].size(); ++j) {
                        if (currentTetromino.shape[i][j] == 1) {
                            grid[currentTetromino.y + i][currentTetromino.x + j] = 1; // 固定方块
                            colors[currentTetromino.y + i][currentTetromino.x + j] = currentTetromino.color; // 设置颜色
                        }
                    }
                }
                // 检查游戏是否失败
                if (currentTetromino.y <= 0) {
                    isPaused = true; // 自动暂停
                    MessageBox(hwnd, L"游戏失败！", L"提示", MB_OK); // 提示信息
                }

                currentTetromino = Tetromino(); // 生成新方块
            }
            else {
                currentTetromino.Move(0, 1); // 向下移动
            }

            InvalidateRect(hwnd, NULL, TRUE); // 触发重绘
        }
        break;


    case WM_KEYDOWN:
        if (isGameStarted && !isPaused) {
            switch (wParam) {
            case VK_LEFT:
                currentTetromino.Move(-1, 0);
                break;
            case VK_RIGHT:
                currentTetromino.Move(1, 0);
                break;
            case VK_DOWN:
                currentTetromino.Move(0, 1);
                break;
            case VK_UP:
                currentTetromino.Rotate();
                break;
            }
            InvalidateRect(hwnd, NULL, TRUE);
        }
        break;

    case WM_DESTROY:
        KillTimer(hwnd, 1); // 关闭定时器
        PostQuitMessage(0);
        break;

    case WM_CREATE: {
        hPauseButton = CreateWindow(
            L"BUTTON", L"暂停",
            WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
            10, 10, 50, 30, // 调整大小
            hwnd, (HMENU)1, (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE), NULL
        );

        hRestartButton = CreateWindow(
            L"BUTTON", L"重来",
            WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
            70, 10, 50, 30, // 调整位置和大小
            hwnd, (HMENU)2, (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE), NULL
        );
    } break;

    case WM_COMMAND:
        if (LOWORD(wParam) == 1) { // 暂停按钮的 ID
            isPaused = !isPaused;
            SetWindowText(hPauseButton, isPaused ? L"继续" : L"暂停");
        }
        else if (LOWORD(wParam) == 2) { // 重来按钮的 ID
            // 重置游戏状态
            isGameStarted = true;
            isPaused = false;
            score = 0;
            SetWindowText(hPauseButton, isPaused ? L"继续" : L"暂停");
            currentTetromino = Tetromino(); // 重新生成初始方块
            memset(grid, 0, sizeof(grid)); // 清空网格
            InvalidateRect(hwnd, NULL, TRUE); // 触发重绘
        }
        SetFocus(hwnd);
        break;


    default:
        return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) {

    const wchar_t CLASS_NAME[] = L"TetrisWindowClass";

    WNDCLASS wc = {};
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = CLASS_NAME;

    RegisterClass(&wc);

    HWND hwnd = CreateWindowEx(
        0, CLASS_NAME, L"俄罗斯方块",
        WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, // 添加 WS_CLIPCHILDREN
        CW_USEDEFAULT, CW_USEDEFAULT, 416, 540,
        NULL, NULL, hInstance, NULL
    );


    if (hwnd == NULL) {
        MessageBox(NULL, L"Failed to create window!", L"Error", MB_ICONERROR);
        return 0;
    }

    ShowWindow(hwnd, nShowCmd);
    UpdateWindow(hwnd); // 更新窗口

    // 设置定时器
    SetTimer(hwnd, 1, 500, NULL); // 每500毫秒触发一次

    // 直接初始化方块
    currentTetromino = Tetromino(); // 生成初始方块

    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}